package com.yunquan.ohana.ui.home.calendar

import android.app.Application
import androidx.databinding.ObservableField
import com.google.gson.Gson
import com.yunquan.ohana.R
import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.entity.FramesEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.utils.ToastUtils
import okhttp3.RequestBody.Companion.toRequestBody

class CalendarViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    val notData = ObservableField(false)

    override fun onEvent(event: EventEntity) {
        super.onEvent(event)
        when (event.type) {
            EventType.FRESH_DEVICE_LIST -> {
                ui.value = 0
            }

            EventType.UPDATE_DEVICE_LIST_COMPLETE -> {
                ui.value = 1
            }

            else -> {}
        }
    }

    fun unbindFrame(item: FramesEntity) {
        val params = mutableMapOf<String, Any>()
        params["deviceIdList"] = arrayListOf(item.id)
        params["delete"] = true
        val jsonGson = Gson().toJson(params)
        val body = jsonGson.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        showLoading()
        BaseHttp.api.unbindDevice(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        ToastUtils.showShort(R.string.unbind_success)
                        RxBus.getDefault().post(EventEntity(EventType.GET_FRAMES))
                    } else {
                        ToastUtils.showShort(R.string.unbind_failed)
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    ToastUtils.showShort(R.string.unbind_failed)
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }
}